<?php
/**
 * Flash Messenger Plugin
 * This injects the flash messenger information into the view so it is available
 * on every page without a lot of work.
 *
 * @package     Visi
 * @subpackage  Controller Plugins
 * @author      Luke Visinoni <luke.visinoni@gmail.com>
 * @copyright   (c) 2010 Luke Visinoni <luke.visinoni@gmail.com>
 * @version     $Id$
 */
class Visi_Controller_Plugin_FlashMessenger extends Zend_Controller_Plugin_Abstract {

    protected $_view;
    
    public function __construct($view = null) {
    
        if (!is_null($view)) {
            $this->setView($view);
        }
    
    }
    
    public function setView(Zend_View_Abstract $view) {
    
        $this->_view = $view;
    
    }
    
    /**
     * The problem here is that this needs to happen after dispatch
     */
    public function postDispatch() {
    
        if (is_null($this->_view)) {
            throw new Visi_Controller_Plugin_Exception('There is no view defined for the FlashMessenger plugin.');
        }
        // Apply the immediate messages
        $messages = Zend_Controller_Action_HelperBroker::getExistingHelper('FlashMessenger')->getImmediateMessages();
        foreach ($messages as $namespace => $messages) {
            foreach ($messages as $message) {
                $this->_view->flash[] = array(
                    'messages' => array($message),
                    'namespace' => $namespace,
                );
            }
        }
        // And add the "next-request" messages
        $messages = Zend_Controller_Action_HelperBroker::getExistingHelper('FlashMessenger')->getAllMessages();
        foreach ($messages as $namespace => $messages) {
            $this->_view->flash[] = array(
                'namespace' => $namespace,
                'messages' => $messages,
            );
        }
    
    }

}